import 'package:safetymonitor/app/components/toast_widget.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/http/http.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/data/entities/auth/dept_resp_entity.dart';
import 'package:safetymonitor/app/data/entities/auth/user_resp_entity.dart';

class SelectPeopleController extends GetxController {
  /// 组织暂存
  List<DeptRespEntity> departmentTemp = [];

  /// 组织数据
  List<DeptRespEntity> department = [];

  /// 人员数据
  List<UserRespEntity> personList = [];

  /// 选择的节点层级
  final List<String> selectedNode = [];

  /// 是否允许退出页面
  bool canPop = true;

  String titleText= '';

  @override
  void onInit() {
    super.onInit();
    if(Get.arguments!=null){
      titleText=Get.arguments['tittle'] as String;
    }else{
      titleText='隐患确认人';
    }

    initData();
  }

  /// 初始化数据
  Future<void> initData() async {
    //获取组织数据
    final res = await HttpUtil().generateGetRequest<List<DeptRespEntity>>(Interface.getCurrentDept).execute(isShowLoading: true);
    res.onSuccess((result) {
      if (result.data != null && result.data!.isNotEmpty) {
        department = result.data!;
        departmentTemp.addAll(department);
      }
      update();
    });
  }

  /// 点击节点名称,查询数据
  Future<void> onClickNode(int index) async {
    selectedNode.removeRange(index, selectedNode.length);
    canPop = selectedNode.isEmpty;
    department.addAll(departmentTemp);
    personList.clear();
    update();
  }

  /// 点击部门
  Future<void> onClickDepartment(int index) async {
    selectedNode.add(department[index].name);
    //获取组织数据
    final res = await HttpUtil().generateGetRequest<List<UserRespEntity>>(
      Interface.getListByDeptId,
      queryParameters: {
        'deptId': department[index].id,
      },
    ).execute(isShowLoading: true);
    res.onSuccess((result) async {
      if (result.data != null && result.data!.isNotEmpty) {
        personList = result.data!;
      }
      canPop = selectedNode.isEmpty;
      department.clear();
      update();
    });
  }

  /// 点击人员
  void onClickPerson(int index) {
    for (var item in personList) {
      item.setIsChecked(false);
    }
    personList[index].setIsChecked(true);
    update();
  }

  /// 退出判断
  void exitJudgment() {
    onClickNode(selectedNode.length - 1);
  }

  /// 确定提交
  Future<void> confirm() async {
    // 找到选中的人员
    final user = personList.firstWhere((element) => element.getIsChecked() == true, orElse: UserRespEntity.new);
    if (user.id == 0 && user.nickname.isEmpty) {
      AppToast.showError('请选择人员');
      return;
    }
    Get.back(result: user);
  }
}
